package com.qf.demo;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ModifyPdfTemplate {
    public static void main(String[] args) throws IOException, DocumentException {
        String templatePath = PathUtil.getCurrentPath()+"template1.pdf";  // 替换为实际的PDF模板路径
        String outputPath = "target/jianli.pdf";      // 替换为输出PDF路径

        try {
            // 读取PDF模板
            PdfReader pdfReader = new PdfReader(templatePath);

            // 创建输出流
            FileOutputStream outputStream = new FileOutputStream(outputPath);

            // 创建PdfStamper，并将模板写入输出流
            PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);

            // 获取模板中的AcroFields（文本域等）
            AcroFields acroFields = pdfStamper.getAcroFields();

            // 设置要填充的数据
            Map<String, String> fieldData = new HashMap<>();
            fieldData.put("name", "李四");
            fieldData.put("sex", "男");

            // 填充文本域
            for (Map.Entry<String, String> entry : fieldData.entrySet()) {
                acroFields.setField(entry.getKey(), entry.getValue());

            }

            // 清除文本域样式，包括边框
            for (Map.Entry<String, AcroFields.Item> entry : acroFields.getFields().entrySet()) {
                PdfDictionary merged = entry.getValue().getMerged(0);
                merged.remove(PdfName.BORDER);
                merged.remove(PdfName.F);
                merged.remove(PdfName.HIGHLIGHT);
            }


            // 关闭 PdfStamper 和 输出流
            pdfStamper.close();
            outputStream.close();

            System.out.println("PDF template modified successfully.");

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}
